#include <fstream>
#include <iostream>
#include <string>

#include "splitter.h"
#include "terrain.h"
#include "terrain_loader.h"

namespace blackjack {

  TerrainLoader::TerrainLoader() {
    // @leezl Do we need to do anything here?
  }

  bool TerrainLoader::loadFromPGM(Terrain *t, std::string fileName) {
    // open the file
    std::string currentLine;
    std::ifstream file(fileName.c_str());
    t->name = fileName;
    
    // check that line one is P2
    getline(file, currentLine);
    if (currentLine != "P2") {
        qDebug()<< "Header incorrect. Exiting." ;
      exit(1);
    } else {
      //qDebug() << "Correct header info. Continuing.";
    }
    
    
    // skip comments
    getline(file, currentLine);
    while (currentLine[0] == '#') {
      //qDebug()<< "Skipping line: " << currentLine;
      getline(file, currentLine);
    }

    std::vector<std::string> coords;
    
    // get the width and height
    //qDebug()<< "Getting width and height info: " << currentLine ;
    split(currentLine, ' ', coords);
    int w = atoi(coords[0].c_str());
    int h = atoi(coords[1].c_str());

    t->setDimensions(w, h);

    coords.clear();

    // get the max value
    getline(file, currentLine);
    //qDebug()<< "Max height value: " << currentLine ;
    
    split(currentLine, ' ', coords);
    h = atoi(coords[0].c_str());

    t->setMaxHeight(h);

    // loop, adding data to data array
    int dataPoint;
    int index = 0;
    t->setTerrainData((int*) malloc(sizeof(int) * t->getHeight() * t->getWidth()));
    while(getline(file, currentLine)) {
      dataPoint = atoi(currentLine.c_str());
      t->getTerrainData()[index++] = dataPoint;
    }

    //qDebug() << "Terrain loaded." ;
    return true;
  }
}
